import { 
  getUserItineraryBookkeepingListAllToTreeForUser,//获取用戶行程記賬列表
  postUserItineraryBookkeepingAddForUser,//添加修改用戶行程記賬
  postUserItineraryBookkeepingDeleteForUser,//刪除用戶行程記賬
  getUserItineraryPayerListAllForUser,//获取用戶行程支付人列表
  postUserItineraryPayerAddForUser,//添加用戶行程支付人
  postUserItineraryPayerDeleteForUser,//刪除用戶行程支付人
  getItineraryInfoByIdForUser,//用戶行程詳情
} from '../../api/home'

Page({
  data: {
    total: 9242,
    showFilter: false,
    showSelect:false,
    nameSelect:'餐飲',
    nameType:'food',
    selectedCategory: null,
    bills: [],
    categories: [
      { type: "food", name: "餐飲", icon: "/pages/assets/image/foodItem.svg",id:1 },
      { type: "play", name: "景點", icon: "/pages/assets/image/playItem.svg",id:2 },
      { type: "shop", name: "購物", icon: "/pages/assets/image/shopItem.svg",id:3 },
      { type: "hotel", name: "住宿", icon: "/pages/assets/image/hotelItem.svg",id:4 },
      { type: "traffic", name: "交通", icon: "/pages/assets/image/trafficItem.svg",id:5 },
      { type: "other", name: "其他", icon: "/pages/assets/image/otherItem.svg",id:6 }
    ],
    currentFilterDate:'',
    amount: '',
    showCursor: false,
    showKeyboard: false,
    keys: ['1','2','3','4','5','6','7','8','9','￥','0','.',],
    keys2: ['1','2','3','4','5','6','7','8','9','$','0','.',],
    priceUnit:'￥',
    delModal: false,//刪除
    timePopup:false,//事件彈框
    weekOptions: [], // ["6.29 星期二", "6.30 星期三", ...]
    hourOptions: [], // ["00", "01", "02", ...]
    minuteOptions: [], // ["00", "01", "02", ...]
    showAddPopup:false,//添加支付人
    showSelectPopup:false,//選擇支付人
    newFolderName: '',
    selectedFolder: '',
    folderList: ['王大壯', '小陳', '小張', '小鐘'], // 模擬的收藏夾
    itinerary_id:'',
    itemDetail:{},
    itineraryDetail:{},
    isScrolling: false, // 是否正在滚动
  },

  onLoad(e) {
    this.setData({
      itinerary_id:e.itinerary_id
    })
    this.getData()
    this.initPickerData();
  },
  async getData() {
    const res = await getUserItineraryBookkeepingListAllToTreeForUser({
      itinerary_id: this.data.itinerary_id
    });
  
    const list = res.data.list || [];
  
    // 累加 sum_amount（确保是数字）
    const total = list.reduce((acc, item) => acc + Number(item.sum_amount || 0), 0);
  
    this.setData({
      bills: list,
      total
    });
  },
  payAddClick(){
    this.setData({
      showAddPopup:true
    })
  },
  // 輸入新收藏夾名稱
  onInputFolderName(e) {
    this.setData({ 
      newFolderName: e.detail.value,
      selectedFolder:''
    });
    console.log(this.data.newFolderName);
  },  

  // 打開選擇收藏夾
  async openSelectPopup() {
    const res = await getUserItineraryPayerListAllForUser({
      itinerary_id:this.data.itinerary_id
    })
    this.setData({ 
      showSelectPopup: true,
      folderList:res.data.list
     });
  },
  openClose(e){
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    this.setData({
      itinerary_payer_id:id,
      name,
      collectModal: true,
    }) 
  },
  // 關閉選擇收藏夾
  closeSelectPopup() {
    this.setData({ showSelectPopup: false });
  },

  // 選擇收藏夾
  chooseFolder(e) {
    this.setData({
      selectedFolder: e.currentTarget.dataset.name,
      'itemDetail.itinerary_payer_name': e.currentTarget.dataset.name,
      'itemDetail.itinerary_payer_id':e.currentTarget.dataset.id,
      newFolderName: '',
      showSelectPopup: false,
      showAddPopup: false,
    });
  },

  // 關閉添加支付人彈框
  closePayPopup() {
    this.setData({ 
      showAddPopup: false ,
      newFolderName: '',
    });
  },
  async addName(){
    const res = await postUserItineraryPayerAddForUser({
      itinerary_id:this.data.itinerary_id,
      name:this.data.newFolderName
    })
    console.log(this.data.newFolderName);
    this.setData({
      'itemDetail.itinerary_payer_name':this.data.newFolderName,
      'itemDetail.itinerary_payer_id':res.data.info.itinerary_payer_id,
      newFolderName:'',
      selectedFolder:''
    })
  },
  // 確認添加
  confirmAdd() {
    const { newFolderName, selectedFolder } = this.data;
    if (!newFolderName && !selectedFolder) {
      wx.showToast({ title: '請輸入或選擇收藏夾', icon: 'none' });
      return;
    }
    if(selectedFolder){
      this.setData({
        showAddPopup: false,
      })
      return
    }
    this.addName()
    wx.showToast({
      title: '添加成功',
    })
    this.setData({
      showAddPopup: false ,
      
    })
  },
  onDayPickerStart() {
    this.setData({
      isScrolling: true
    })
  },

  // 滚动结束
  onDayPickerEnd() {
    this.setData({
      isScrolling: false
    })
  },
  // 確認時間
  selectTimeClick() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }

    const { selectedTime } = this.data;
    if (!selectedTime) return;
  
    // 提取 day_num
    const dayMatch = selectedTime.week.match(/DAY (\d+)/);
    const day_num = dayMatch ? parseInt(dayMatch[1], 10) : null;
  
    // 拼接时间字符串
    const time = `${selectedTime.hour}:${selectedTime.minute}`;
  
    console.log('day_num:', day_num, 'time:', time);
  
    // 这里你可以保存到 data 或提交接口
    this.setData({
      'itemDetail.day_num':day_num,
      'itemDetail.time':time,
      timePopup: false
    });
  },
  // 關閉時間彈框
  closePopup(){
    this.setData({
      timePopup:false,
      collectModal:false
    })
  },
  selectEnd(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    const week = this.data.weekOptions[val[0]];
    const hour = this.data.hourOptions[val[1]];
    const minute = this.data.minuteOptions[val[2]];
  
    console.log('當前選擇：', week, hour, minute);
  
    // 保存为对象
    this.setData({
      selectedTime: {
        week,
        hour,
        minute
      },
      // 如果你需要拼接成 "YYYY-MM-DD HH:MM" 格式
      selectedTimeString: `${week} ${hour}:${minute}`
    });
  },
  // 初始化選擇器數據
  async initPickerData() {
    const res = await getItineraryInfoByIdForUser({
      itinerary_id: this.data.itinerary_id
    });
    const days = res.data.list_item.map(item => `DAY ${item.day_num}`);

    // 小時
    const hours = [];
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i : '' + i);
    }

    // 分鐘
    const minutes = [];
    for (let i = 0; i < 60; i++) {
      minutes.push(i < 10 ? '0' + i : '' + i);
    }

    // 設置默認索引值 [第0天, 0小時, 0分鐘]
    const defaultValue = [0, 0, 0];

    this.setData({
      itineraryDetail:res.data.info,
      weekOptions: days,
      hourOptions: hours,
      minuteOptions: minutes,
      selectEndValue: defaultValue, // picker-view 默認顯示的值
      selectedTime: {
        week: days[0],
        hour: hours[0],
        minute: minutes[0]
      },
      selectedTimeString: `${days[0]} ${hours[0]}:${minutes[0]}`
    });
  },
  showCustomKeyboard(e) {
    
  const record = e.currentTarget.dataset.record
  if (record.time && typeof record.time === 'string') {
    const parts = record.time.split(':');
    let hour = parts[0] ? parts[0].padStart(2, '0') : '00';
    let minute = parts[1] ? parts[1].padStart(2, '0') : '00';
    record.time = `${hour}:${minute}`;
  }
    // 类型映射表
  const typeMap = {
    1: 'food',
    2: 'play',
    3: 'shop',
    4: 'hotel',
    5: 'traffic',
    6: 'other'
  };

  const typeMap2 = {
    1: '餐飲',
    2: '景點',
    3: '購物',
    4: '住宿',
    5: '交通',
    6: '其他'
  };

  const typeName = typeMap[record.type] || '';
  const typeName2 = typeMap2[record.type] || '';
    
    this.setData({
      nameType:typeName,
      nameSelect:typeName2,
      itemDetail:record,
      showKeyboard: true,
      showCursor: true,
      selectedFolder:''
    })
    console.log(record);
  },

  onKeyTap(e) {
    const val = e.currentTarget.dataset.val;
    if(val=='￥'){
      this.setData({ 
        priceUnit:'$'
       });
       return
    }
    if(val=='$'){
      this.setData({ 
        priceUnit:'￥'
       });
       return
    }

    let amount = this.data.itemDetail.amount || "";

    // 小数点只允许出现一次
    if (val === '.' && amount.includes('.')) {
      return;
    }
    // 拼接金额
    amount = amount + val;
    this.setData({ 
      'itemDetail.amount':amount
     });
  },

  onDelete() {
    let amount = this.data.itemDetail.amount.slice(0, -1);
    this.setData({ 
      'itemDetail.amount':amount
     });
  },
  // 监听输入
  onRemarkInput(e) {
    this.setData({
      'itemDetail.title': e.detail.value
    })
  },
  onClose(){
    this.setData({
      showKeyboard: false,
      showCursor: false,
    });
  },
  async onConfirm() {
    console.log(this.data.itemDetail);
    const itemDetail =this.data.itemDetail
    itemDetail.itinerary_id=this.data.itinerary_id
    const res = await postUserItineraryBookkeepingAddForUser(itemDetail)
    this.getData()
    wx.showToast({
      title: '編輯成功',
    })
    this.setData({
      showKeyboard: false,
      showCursor: false,
      amount:''
    });
  },
  delClick(){
    this.setData({
      delModal:true
    });
  },

  closeModal(){
    this.setData({
      delModal:false
    });
  },
  //刪除賬單
  async confirmDelete(){
    const res = await postUserItineraryBookkeepingDeleteForUser({
      itinerary_id:this.data.itinerary_id,
      itinerary_bookkeeping_id:this.data.itemDetail.itinerary_bookkeeping_id
    })
    wx.showToast({
      title: '刪除成功',
    })
    this.getData()
    this.setData({
      delModal:false,
      showKeyboard:false
    });
  },
  async confirmDeleteMan(){
    const res = await postUserItineraryPayerDeleteForUser({
      itinerary_id:this.data.itinerary_id,
      itinerary_payer_id:this.data.itinerary_payer_id
    })
    this.openSelectPopup()
    wx.showToast({
      title: '刪除成功',
    })
    this.setData({
      collectModal:false
    });
  },
  openFilter(e) {
    const date = e.currentTarget.dataset.date
    this.setData({
      showFilter: true, 
      currentFilterDate: date // 記錄當前點開的日期
    })
  }, 

  closeFilter() {
    this.setData({ 
      showFilter: false,
      showSelect: false,
     });  
  },
  allCategory(){
    this.setData({ showFilter: false });
  },
  selectCategory(e) {
    this.setData({ showFilter: false });
  }, 
  showItemSelect(){
    this.setData({  
      showSelect: true,
     });
  },
  showDaySelect() {
    const itemDetail = this.data.itemDetail;

    let selectEndValue = [itemDetail.day_num - 1, 0, 0];
  
    if (itemDetail.time) {
      const [hourStr, minuteStr] = itemDetail.time.split(":");
      const hour = Number(hourStr);
      const minute = Number(minuteStr);
  
      selectEndValue = [itemDetail.day_num - 1, hour, minute];
    }
  
    this.setData({
      timePopup: true,
      selectEndValue
    });
  
    console.log("设置选择器默认值：", selectEndValue);
  },  
  selectClick(e){
    const name = e.currentTarget.dataset.name
    const type = e.currentTarget.dataset.type
    const id = e.currentTarget.dataset.id
    
    this.setData({  
      showFilter: false,
      showSelect: false,
      nameSelect:name,
      nameType:type,
      'itemDetail.type':id
     });
     console.log(this.data.itemDetail);
  },
});
